package com.sixmac.controller;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.sixmac.GlobalInterceptor;
import com.sixmac.annotation.AuthUser;
import com.sixmac.core.annotation.Validator;
import com.sixmac.core.base.model.Format;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.plugins.dao.Db;
import com.sixmac.core.toolbox.CMap;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.grid.BladePage;
import com.sixmac.core.toolbox.support.Convert;
import com.sixmac.model.*;
import com.sixmac.service.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by admin on 2018/7/3.
 */
@Controller
public class IndexCcontroller extends ApiController {
    @Autowired
    IndexService indexService;


    /**
     * @api {post} /api/index   首页
     * @apiName index.login
     * @apiGroup logind
     * @apiParam {String}  name  搜索值，可以为空
     * @apiParam {String}  page  当前页 默认为1
     * @apiParam {String}  size  每页大小 默认为6
     * @apiSuccess {String} data.rows.id 课程id
     * @apiSuccess {String} data.rows.image 封面图片
     * @apiSuccess {String} data.rows.num 播放量
     * @apiSuccess {String} data.rows.point 学习要点&考点(富文本)
     * @apiSuccess {String} data.rows.firstUrl 简介视频
     * @apiError {Integer} 1
     */
    @RequestMapping("/index")
    public AjaxResult index(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "6") Integer size, String name) {
        StringBuilder sb = new StringBuilder();
        sb.append("select id,name,(select m.url from t_course_chapter c inner join t_media m on m.id = c.url  where c.url is not null and c.url != 0  and c.courseId = a.id order by c.sort limit 0,1)firstUrl,content as point,image,url,pid,ifnull(playnum,0)num,createtime,updatetime,level from t_course_chapter a where pid = 0  ");
        if (name != null) {
            sb.append(" and name like '%" + name + "%'");
        }
        sb.append("order by createtime desc");
        BladePage<Map> mapBlade = Db.paginate(sb.toString(), null, page, size);
        return json(mapBlade);
    }

    /**
     * @api {post} /api/catalog   目录
     * @apiName index.catalog
     * @apiGroup index
     * @apiParam {String}  token  token登录的用户必须传入，游客不用传入
     * @apiParam { String}  courseId  课程Id
     * @apiSuccess {String} data.rows.name 目录的名称
     * @apiSuccess {String} data.rows.safety  安全技术(富文本) 1显示按钮（灰色） 2不显示3显示已点击（蓝色）
     * @apiSuccess {String} data.rows.technology  技术要求(富文本)1显示按钮（灰色） 2不显示3显示已点击（蓝色）
     * @apiSuccess {String} data.rows.video  微课视频 1显示按钮（灰色） 2不显示3显示已点击（蓝色）4显示合格
     * @apiSuccess {String} data.rows.test  章节测试 1显示按钮（灰色） 2不显示3显示已点击（蓝色）
     * @apiSuccess {String} data.rows.levelName 级别
     * @apiSuccess {String} data.rows.simulation  模拟训练（不管这个字段，以后可能有用）
     * @apiSuccess {String} data.rows.courseChapterId 微课视频 如果为null或者为空，则不显示该按钮 通过这个id调用视频
     * @apiSuccess {String} data.rows.list 如果章节下面有章节，则list不为空
     * @apiSuccess {String} data.rows.status 1未完成 2完成
     * @apiError {Integer} 1
     */
    @AuthUser(requisite = false)
    @RequestMapping("/catalog")
    @Validator(name = {"courseId"}, format = {Format.NOT_NULL})
    public AjaxResult catalog(ClienUser user, Integer courseId) {


        if (user == null) {

            System.out.println(123);

            return indexService.catalog(courseId, null);
        }
        return indexService.catalog(courseId, user.getId());
    }

    /**
     * @api {post} /api/courseChapterId   知识点
     * @apiName index.courseChapterId
     * @apiGroup index
     * @apiParam {String}  token  token(登录用户必须传入token)
     * @apiParam {String}  courseId  课程id
     * @apiParam {String}  courseChapterId  微课视频的id （catalog接口中的courseChapterId）
     * @apiSuccess {String} data.rows.content 知识点简介
     * @apiSuccess {String} data.rows.image 章节图片
     * @apiSuccess {String} data.rows.url  视频地址
     * @apiSuccess {String} data.rows.levelName 级别
     * @apiSuccess {String} data.rows.simulation  模拟训练（不管这个字段，以后可能有用）
     * @apiSuccess {String} data.rows.courseChapterId 微课视频 如果为null或者为空，则不显示该按钮 通过这个id调用视频
     * @apiSuccess {String} data.rows.test  章节测试id
     * @apiError {Integer} 1
     */
    @AuthUser(requisite = false)
    @RequestMapping("/courseChapterId")
    @Validator(name = {"courseChapterId", "courseId"}, format = {Format.NOT_NULL, Format.NOT_NULL})
    public AjaxResult getVideoByCourseChapterId(ClienUser user, Integer courseChapterId, Integer courseId) {
        if (user != null) {
            indexService.updateClientUserChapterRecord(user.getId(), courseChapterId, 3, courseId);
        }
        CourseChapter courseChapter = Blade.create(CourseChapter.class).findById(courseChapterId);
        if (!Strings.isNullOrEmpty(courseChapter.getUrl())) {
            Media media = Blade.create(Media.class).findById(courseChapter.getUrl());
            courseChapter.setUrl(media.getUrl());
        }

        return json(courseChapter);
    }

    /**
     * @api {post} /api/getText   获取安全技术或者技术要求
     * @apiName index.getText
     * @apiGroup index
     * @apiParam {String}  token  token
     * @apiParam {String}  courseChapterId  （catalog接口中的courseChapterId）
     * @apiParam {String}  courseId  课程id
     * @apiParam {String}  type  1表示安全技术2表示技术要求
     * @apiSuccess {String} data.rows.content  (富文本)
     * @apiError {Integer} 1
     */
    @AuthUser(isGuess = false)
    @RequestMapping("/getText")
    @Validator(name = {"type", "courseChapterId"}, format = {Format.NOT_NULL, Format.NOT_NULL})
    public AjaxResult getText(ClienUser user, Integer type, Integer courseChapterId, Integer courseId) {
        String s;
        CourseChapter courseChapter = Blade.create(CourseChapter.class).findById(courseChapterId);
        if (courseChapter == null) {
            return error("章节找不到");
        }
        if (type == 1) {
            s = courseChapter.getSafety();
        } else {
            s = courseChapter.getTechnology();
        }


        indexService.updateClientUserChapterRecord(user.getId(), courseChapterId, type, courseId);
        return json(getCMap().put("content", s));
    }


    /**
     * @api {post} /api/showComment   显示评论
     * @apiName index.showComment
     * @apiGroup index
     * @apiParam {String}  courseChapterId  章节id
     * @apiParam {String}  page  当前页 默认为1
     * @apiParam {String}  size  每页大小 默认为6
     * @apiSuccess {String} data.rows.content 评论内容
     * @apiSuccess {String} data.rows.createtime 创建时间
     * @apiSuccess {String} data.rows.name 评论名字
     * @apiSuccess {String} data.rows.headimg 头像
     * @apiError {Integer} 1
     */
    @RequestMapping("showComment")
    public AjaxResult showComment(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "6") Integer size, Integer courseChapterId) {
        return json(Db.paginate("select c.*,u.name,u.headimg from t_comment c   left join t_user u on u.id = c.userId  where courseChapterId =  #{courseChapterId} ", getCMap().put("courseChapterId", courseChapterId), page, size));
    }

    /**
     * @api {post} /api/editComment   评论
     * @apiName index.editComment
     * @apiGroup index
     * @apiParam {String}  token  token
     * @apiParam {String}  courseChapterId  微课视频的id 也是章节的id（catalog接口中的courseChapterId）
     * @apiParam {String} userId 用户id
     * @apiParam {String} content 用户评论内容
     * @apiError {Integer} 1
     */
    @AuthUser(isGuess = false)
    @RequestMapping("/editComment")
    @Validator(name = {"courseChapterId", "content"}, format = {Format.NOT_NULL, Format.NOT_NULL})
    public AjaxResult editComment(ClienUser user, Integer courseChapterId, String content) {
        Comment comment = new Comment();
        comment.setUserId(user.getId());
        comment.setCourseChapterId(courseChapterId);
        comment.setContent(content);
        comment.setCreatetime(new Date());
        comment.setUpdatetime(new Date());
        Boolean b = Blade.create(Comment.class).save(comment);
        if (b) {
            return success("评论成功");
        } else {
            return error("评论失败");
        }
    }

    /**
     * @api {post} /api/getExaminTest   章节测试()
     * @apiName index.getExaminTest
     * @apiGroup index
     * @apiDescription 批量返回所有题目的ids
     * @apiParam {String}  token  token
     * @apiParam {String}  courseId  课程id
     * @apiParam {String}  courseChapterId  章节id
     * @apiSuccess {String} data.rows.examin.examinTime 考试时间分钟为单位（章节测试不要）
     * @apiSuccess {String} data.rows.topic.reach 理由
     * @apiSuccess {String} data.rows.examin.image 题目图片
     * @apiSuccess {String} data.rows.examin.pass 分数（都是100章节测试不要分数）
     * @apiSuccess {String} data.rows.examin.require 考试要求（章节测试不要）
     * @apiSuccess {String} data.rows.examin.title 考试标题（章节测试不要）
     * @apiSuccess {String} data.rows.info.count 题目数量
     * @apiSuccess {String} data.rows.info.ids 题目的ids
     * @apiError {Integer} 1
     */
    @AuthUser(isGuess = false)
    @RequestMapping("/getExaminTest")
    public AjaxResult getExaminTest(ClienUser user, Integer courseChapterId, Integer courseId) {
        indexService.updateClientUserChapterRecord(user.getId(), courseChapterId, 5, courseId);
        CourseChapter courseChapter = Blade.create(CourseChapter.class).findById(courseChapterId);
        if (courseChapter == null) {
            return error("章节测试id找不到");
        }
        Examin examin = Blade.create(Examin.class).findById(courseChapter.getTest());
        if (examin == null) {
            return error("考试找不到");
        }
        Map map = Db.selectOne("select count(*) as count,group_concat(id) as ids from t_examin_topic t where t.examineId = #{id}", getCMap().put("id", courseChapter.getTest()));
        String ids[] = Convert.toStr(map.get("ids")).split(",");
        Map m = getCMap().put("examin", examin).put("info", map).put("ids", ids);
        return json(m);
    }


    /**
     * @api {post} /api/getQuestion   获取问题
     * @apiName index.getQuestion
     * @apiGroup index
     * @apiParam {String}  token  token
     * @apiParam {String}  id  题目id
     * @apiSuccess {String} data.rows.topic.choice 1单选 2多择题3判断题
     * @apiSuccess {String} data.rows.topic.image 题目图片为空则不显示，多个图片用,分隔
     * @apiSuccess {String} data.rows.topic.isTrue 正确答案，多选题目用,分隔
     * @apiSuccess {String} data.rows.topic.name 题目
     * @apiSuccess {String} data.rows.list.content 问题内容
     * @apiError {Integer} 1
     */
    @AuthUser(isGuess = false)
    @RequestMapping("/getQuestion")
    public AjaxResult getQuestion(Integer id) {
        ExaminTopic examinTopic = Blade.create(ExaminTopic.class).findById(id);
        if (examinTopic == null) {
            return error("题目找不到");
        }
        List<ExaminTopicAnswer> answerList = Blade.create(ExaminTopicAnswer.class).findBy("topicId =#{id}", getCMap().put("id", id));
        Map map = getCMap().put("topic", examinTopic);
        map.put("answer", answerList);
        return json(map);

    }

    /**
     * @api {post} /api/finshVide   视频看完调用这个接口
     * @apiName index.finshVide
     * @apiGroup index
     * @apiParam {String}  token  token
     * @apiParam {String}  examinId  课程id
     * @apiParam {String}  courseChapterId  courseChapterId
     * @apiSuccess {String} data.rows.answer.chapterId 章节id
     * @apiError {Integer} 1
     */
    @AuthUser(isGuess = false)
    @RequestMapping("/finshVide")
    public AjaxResult finshVide(ClienUser user, Integer courseChapterId, Integer examinId) {
        indexService.updateClientUserChapterRecord(user.getId(), courseChapterId, 4, examinId);
        return success("成功");
    }

    /**
     * @api {post} /api/recent   继续上次学习进度(游客不建议调用这个接口)
     * @apiName index.recent
     * @apiGroup index
     * @apiParam {String}  token  token
     * @apiError {Integer} 1
     */
    @AuthUser()
    @RequestMapping("/recent")
    public AjaxResult recent(ClienUser user, Integer courseId) {
        if (user.getId() == 0) {
            return success("游客不能访问");
        }
        String sql = " select * from t_user_chapter_record r where  userId =#{uid} order  by r.createTime desc";
        Map map = Db.selectOne(sql, getCMap().put("uid", user.getId()));
        if (map != null) {
            return indexService.getPid(courseId, Convert.toInt(map.get("chapterId")));
        } else {
            return error("找不到章节");
        }

    }

    /**
     * @api {post} /api/calcu   最近在学
     * @apiName index.calcu
     * @apiGroup index
     * @apiParam {String}  token  token
     * @apiParam {String}  courseId  课程id
     * @apiSuccess {String} s 百分比
     * @apiSuccess {String} name 章节名称
     * @apiSuccess {String} chapterId 章节id
     * @apiError {Integer} 1 没有发现最近学习记录
     */
    @AuthUser()
    @RequestMapping("/calcu")
    public AjaxResult calcu(ClienUser user, Integer courseId) {
        return indexService.calu(courseId, user.getId());
    }

    /**
     * @api {post} /api/getExaminById   通过题目的id获取题目(章节测试)
     * @apiName index.getExaminById
     * @apiGroup index
     * @apiParam {String}  id  题目id
     * @apiSuccess {String} data.rows.topic.choice 1单选 2多择题3判断题
     * @apiSuccess {String} data.rows.topic.image 题目图片为空则不显示，多个图片用,分隔
     * @apiSuccess {String} data.rows.topic.isTrue 正确答案，多选题目用,分隔
     * @apiSuccess {String} data.rows.topic.name 题目
     * @apiSuccess {String} data.rows.list.content 问题内容
     * @apiError {Integer} 1
     */
    @RequestMapping("/getExaminById")
    public AjaxResult getExaminById(Integer id) {
        ExaminTopic examinTopic = Blade.create(ExaminTopic.class).findById(id);
        if (examinTopic == null) {
            return error("题目找不到");
        }
        List lists = Blade.create(ExaminTopicAnswer.class).findBy("topicId=#{id}", getCMap().put("id", examinTopic.getId()));
        Map map = getCMap().put("topic", examinTopic).put("list", lists);
        return json(map);
    }

    /**
     * @api {post} /api/getExaminList   通过题目的ids返回所有题目
     * @apiName index.getExaminList
     * @apiGroup index
     * @apiDescription 批量返回所有题目lists集合
     * @apiParam {String}  token  token
     * @apiParam {String}  ids  考试题目的ids
     * @apiSuccess {String} data.rows.topic.choice 1单选 2多择题3判断题
     * @apiSuccess {String} data.rows.topic.image 题目图片为空则不显示，多个图片用,分隔
     * @apiSuccess {String} data.rows.topic.isTrue 正确答案，多选题目用,分隔
     * @apiSuccess {String} data.rows.topic.name 题目
     * @apiSuccess {String} data.rows.list.content 问题内容
     * @apiSuccess {String} data.rows.info.total 题目数量
     * @apiError {Integer} 1
     */
    @AuthUser(isGuess = false)
    @RequestMapping("/getExaminList")
    public AjaxResult getExaminList(ClienUser user, String ids) {
        AjaxResult res = new AjaxResult();
        List<Map> list = Db.selectList(" select t.id,t.examineId,t.name,t.choice,t.image,t.reach,t.isTrue,a.content from t_examin_topic t inner join t_examin_topic_answer a on t.id=a.topicId  where 1=1 and t.id in (#{join(ids)})", CMap.init().put("ids", Convert.toStrArray(ids)));
        return res.setData(CMap.init().put("list", list).put("total", list.size()));
    }

    /**
     * @api {post} /api/number   在线人数
     * @apiName index.number
     * @apiGroup index
     * @apiDescription 批量返回所有题目lists集合
     * @apiSuccess {String} data.rows.topic.number 请求人数
     * @apiError {Integer} 1
     */
    @RequestMapping("/number")
    public AjaxResult number() {
        long i = GlobalInterceptor.cache.size();
        return json(getCMap().put("number", i));
    }


    /**
     * @api {post} /api/videoList   视频列表
     * @apiName index.videoList
     * @apiGroup index
     * @apiDescription 返回该章节下的所有视频
     * @apiParam {Integer}  courseChapterId  微课视频的id （
     * @apiSuccess {String} data.rows.topic.id 该章节的id
     * @apiSuccess {String} data.rows.topic.image 视频封面图片
     * @apiSuccess {String} data.rows.topic.name 视频名称
     * @apiSuccess {String} data.rows.topic.url 视频地址
     * @apiError {Integer} 1
     */
    @RequestMapping("/videoList")
    public AjaxResult videoList(Integer courseChapterId) {
        CourseChapter courseChapter = Blade.create(CourseChapter.class).findById(courseChapterId);
        if (courseChapter == null) {
            return error("该章节视频不存在");
        }
        List<Map> list = Lists.newArrayList();

        List<Map> courseChapterList = Db.selectList("select id,image,name,(select url from t_media where id = cc.url)as url from t_course_chapter cc where pid = " + courseChapter.getPid());
        for (Map map : courseChapterList) {
            if (!Strings.isNullOrEmpty(Convert.toStr(map.get("url")))) {
                list.add(map);
            }
        }
        return json(getCMap().put("list", list));
    }


}
